package rabbitmq

import (
	"fmt"
	"github.com/streadway/amqp"
	"log"
)

var (
	Conn *amqp.Connection
)

func InitRabbitMq(host, port, username, password string) error {
	conn, err := amqp.Dial(fmt.Sprintf("amqp://%s:%s@%s:%s/", username, password, host, port))
	if err != nil {
		return err
	}
	Conn = conn
	log.Printf("mq conn : %v \n", Conn)
	return nil
}

func GetQueue(queueName string, args amqp.Table) (amqp.Queue, *amqp.Channel, error) {
	q := amqp.Queue{}
	ch, err := Conn.Channel()
	if err != nil {
		return q, nil, err
	}
	//用于检查队列是否存在,已经存在不需要重复声明
	q, err = ch.QueueDeclarePassive(queueName, false, false, false, true, args)
	if err != nil {
		fmt.Printf("QueueDeclarePassive失败:%s \n", err)
		// 队列不存在,声明队列
		// name:队列名称;durable:是否持久化,队列存盘,true服务重启后信息不会丢失,影响性能;autoDelete:是否自动删除;noWait:是否非阻塞,
		// true为是,不等待RMQ返回信息;args:参数,传nil即可;exclusive:是否设置排他
		q, err = ch.QueueDeclare(queueName, false, false, false, true, args)
		if err != nil {
			fmt.Printf("MQ注册队列失败:%s \n", err)
			return q, nil, err
		}
	}
	return q, ch, nil
}
